import routes from '@/router/routes'
import { createRouter, createWebHistory } from 'vue-router'
import { useGlobalConfig } from '@/stores/globalConfig'
import { TOKEN_NAME } from '@/const'

const adminPath = '/console'
const loginPath = '/login'
const router = createRouter({
	history: createWebHistory(import.meta.env.VITE_APP_SITE_BASE_URL),
	routes: routes,
	scrollBehavior() {
		return {
			top: 0
		}
	}
})
router.beforeEach(async (to, from, next) => {
	const gc = useGlobalConfig()
	const token: string | null = localStorage.getItem(TOKEN_NAME)
	gc.startLoading()

	if (token) {
		if (to.path === loginPath) {
			await next({
				path: adminPath
			})
		} else {
			await next()
		}
	} else {
		if (to.path === loginPath) {
			await next()
		} else {
			if (to.path.startsWith(adminPath)) {
				await next(loginPath)
			} else {
				await next()
			}
		}
	}
	setTimeout(() => {
		gc.finishLoading()
	}, 300)
})
export default router
